package top.jacktgq.itheima.nio.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

/**
 * @Author CandyWall
 * @Date 2021/3/19--6:10
 * @Description
 */
@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
        // 使用nio来理解阻塞模式
        // 0.ByteBuffer
        ByteBuffer buffer = ByteBuffer.allocate(16);
        // 1.创建服务器
        ServerSocketChannel ssc = ServerSocketChannel.open();
        //设置为非阻塞模式
        ssc.configureBlocking(false);

        // 2.绑定监听端口
        ssc.bind(new InetSocketAddress(8080));

        // 3.建立连接集合
        ArrayList<SocketChannel> channels = new ArrayList<>();
        while (true) {
            // 4.接受请求，建立与客户端的连接,SocketChannel用来与客户端通信
            SocketChannel socketChannel = ssc.accept(); // 如果没有连接建立，accept不会阻塞，但sc是null
            if (socketChannel != null) {
                log.debug("connected..." + socketChannel);
                // 设置为非阻塞模式
                socketChannel.configureBlocking(false);
                channels.add(socketChannel);
            }
            // 5.接收客户端发送的数据
            for (SocketChannel channel : channels) {
                int readCount = channel.read(buffer);// 非阻塞，线程仍然会继续运行，如果没有读到数据，read会返回0
                if (readCount > 0) {
                    buffer.flip();
                    System.out.println(StandardCharsets.UTF_8.decode(buffer));
                    buffer.clear();
                    log.debug("after read..." + channel);
                }
            }
        }
    }
}
